<?php

namespace addons\venue\controller;

use addons\venue\library\Wxlogin;
use app\admin\model\venue\Detail;
use app\admin\model\venue\user\Signin;
use app\admin\model\venue\user\Store;
use app\common\controller\Api;
use app\admin\model\User as U;
use app\common\model\ScoreLog;
use think\Request;
use think\Validate;

use addons\venue\library\Jssdk;
use addons\venue\library\MpWechat;


class User extends Api
{

    protected $noNeedLogin = ['login','loginWxOfficial','getjssdk','getjmlogin'];
    protected $noNeedRight = ['*'];

    protected $config = "";

    public function __construct(Request $request = null)
    {
        $this->config = get_addon_config("venue");
        parent::__construct($request);
    }

    /*
     * 注册/登录
     */
    public function login(){
        $encryptdata = $this->request->post('encryptedData');
        $iv          = $this->request->post('iv');
        $code        = $this->request->post('code');
        $platform = $this->request->header("platform")? $this->request->header("platform") : 'miniapp';
        if (empty($code) || !$encryptdata || !$iv) {
            $this->error('请求数据不能为空');
        }
        //微信授权登录
        $login = new Wxlogin();
        $res   = $login->login($code,$encryptdata,$iv);
        if (!$res["code"]){
            $this->error($res['msg']);
        }
        $openId = $res['data']['openid'];
        $mobile = $res['data']['mobile'];
        //查询用户表是否存在此open_id,存在则登录,不存在则注册
        $detail = Detail::get(["openid"=>$openId]);
        if ($detail){
            $user = U::get(["id"=>$detail['user_id']]);
            if (!$user){
                Detail::destroy($detail['id']);
                $detail = Detail::get(["openid"=>$openId]);
            }
        }
        if ($detail){

            if ($user['status'] == 'hidden'){
                $this->error("该用户已被禁用");
            }
            //登录
            $ret = $this->auth->direct($user->id);
            if ($ret) {
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success("登录成功", $data);
            } else {
                $this->error($this->auth->getError());
            }
        }else{
            //注册
            $username   = "微信用户".chr(rand(65,90)).chr(rand(97,122)).chr(rand(65,90)).chr(rand(97,122)).substr($mobile,-4);
            //判断用户是否用手机号注册过 如果注册过 绑定微信号
            $info = U::get(["mobile"=>$mobile]);
            if ($info){
                //更新用户表中的openid
                if (Detail::get(["user_id"=>$info['id']])){
                    Detail::update(["openid"=>$openId],["user_id"=>$info->id]);
                }else{
                    Detail::create(["openid"=>$openId,"user_id"=>$info->id,"platform" => $platform]);
                }

                $this->auth->direct($info->id);
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success("登录成功", $data);
            }else{
                $ret = $this->auth->register($username, "", "", $mobile,[]);
                if ($ret) {
                    $user = \app\common\model\User::get($this->auth->id);
                    $user->avatar = '/assets/img/avatar.png';
                    $user->save();
                    Detail::create([
                        "user_id"=>$this->auth->id,
                        "openid"=>$openId,
                        "platform" => $platform,
                    ]);
                    $data = ['userinfo' => $this->auth->getUserinfo()];
                    $this->success(__('注册成功'), $data);
                } else {
                    $this->error($this->auth->getError());
                }
            }
        }
    }

    /*
     * 注册/登录
     */
    public function loginWxOfficial(){
        $platform = $this->request->header('platform', 'wechat');
        $code        = $this->request->post('code');
        $parent_id = $this->request->header("pid")??0;

        $mpwechat = new MpWechat();
        $param['code'] = $code;
        $backuserinfo = $mpwechat->getUserInfo($param);
        if (!$backuserinfo) {
            $this->error(__('操作失败'));
        }
        $openId = $backuserinfo['openid'];
        $mobile = '';
        //查询用户表是否存在此open_id,存在则登录,不存在则注册
        $detail = Detail::get(["openid"=>$openId]);
        if ($detail){
            $user = U::get(["id"=>$detail['user_id']]);
            if (!$user){
                Detail::destroy($detail['id']);
                $detail = Detail::get(["openid"=>$openId]);
            }
        }
        if ($detail){

            if ($user['status'] == 'hidden'){
                $this->error("该用户已被禁用");
            }
            //登录
            $ret = $this->auth->direct($user->id);
            if ($ret) {
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success("登录成功", $data);
            } else {
                $this->error($this->auth->getError());
            }
        }else{
            //注册
            $username   =  $backuserinfo['userinfo']['nickname'].chr(rand(65,90)).chr(rand(97,122)).chr(rand(65,90)).chr(rand(97,122)).substr($mobile,-4);
            //判断用户是否用手机号注册过 如果注册过 绑定微信号
            $info = false;
            if ($info){
                //更新用户表中的openid
                if (Detail::get(["user_id"=>$info['id']])){
                    Detail::update(["openid"=>$openId],["user_id"=>$info->id]);
                }else{
                    Detail::create(["openid"=>$openId,"user_id"=>$info->id,"platform" => $platform]);
                }

                $this->auth->direct($info->id);
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success("登录成功", $data);
            }else{
                $ret = $this->auth->register($username, "", "", $mobile,[]);
                if ($ret) {
                    $user = \app\common\model\User::get($this->auth->id);
                    $user->avatar = $backuserinfo['userinfo']['avatar'] ? $backuserinfo['userinfo']['avatar'] :  '/assets/img/avatar.png';
                    $user->save();
                    Detail::create([
                        "user_id"=>$this->auth->id,
                        "openid"=>$openId,
                        "platform" => $platform,

                    ]);
                    $data = ['userinfo' => $this->auth->getUserinfo()];
                    $this->success(__('注册成功'), $data);
                } else {
                    $this->error($this->auth->getError());
                }
            }
        }
    }

    public function getjssdk(){
        //$config = get_addon_config('zsff');
        $config = $this->config;
        $urls = $this->request->post('urls');
        $fzwechat =  new Jssdk($config['wechat']['app_id'] ,$config['wechat']['app_secret'] );
        $data['signData'] =$fzwechat->GetSignPackage($urls);
        $this->success(__('成功'), $data);

    }
        
    public function getjmlogin(){
        $urls = $this->request->post('urls');
        $data['url'] =  (new MpWechat)->getAuthorizeUrl($urls);
        $this->success(__('成功'), $data);
        
    }
    
    /*
     * 修改会员个人信息
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $mobile = $this->request->post('mobile');
        $birthday = $this->request->post('birthday');
        $file = $this->request->post('file');

        if (empty($username) || empty($mobile)){
            $this->error("用户名或者手机号不能为空");
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error("手机号不符合规则");
        }
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error("该用户名已存在");
            }
            $user->username = $username;
        }
        $user->avatar  = $file;
        $user->username = $username;
        $user->mobile   = $mobile;
        $user->birthday    = $birthday;
        $user->save();
        $this->success("修改成功");
    }

    /*
     * 手机号绑定微信账号
     */
    public function binding(){
        $userId = $this->auth->id;
        $code        = $this->request->post('code');
        //查询该用户是否已绑定
        $user = Detail::get(["user_id"=>$userId]);
        if (!empty($user['openid'])){
            $this->error("已绑定，无需重复绑定");
        }
        if (empty($code)) {
            $this->error('code不能为空');
        }
        //微信授权登录
        $login = new Wxlogin();
        $res   = $login->get_openid($code);
        if (!$res["code"]){
            $this->error($res['msg']);
        }

        $openId = $res['data']['openid'];
        //更新用户表中的openid
        $user->openid = $openId;
        $user->save();

        $data['openId'] = $res['data']['openid'];
        $this->success("返回成功",$data);
    }


    /*
     * 获取用户的openid
     */
    public function getopenid(){
        $userId = $this->auth->id;
        $code        = $this->request->post('code');
     
        if (empty($code)) {
            $this->error('code不能为空');
        }
        //微信授权登录
        $login = new Wxlogin();
        $res   = $login->get_openid($code);
        if (!$res["code"]){
            $this->error($res['msg']);
        }

        $data['openid'] = $res['data']['openid'];

        $this->success("获取成功",$data);
    }

    /*
     * 获取会员个人信息
     */
    public function getUserInfo()
    {
        $user = $this->auth->id;
        $userInfo = U::where("id",$user)->field("avatar,username,birthday,level,mobile,money,score")->find();
        $userInfo['interests'] = explode(',',$this->config['interests']);
        $detail = Detail::get(["user_id"=>$user]);
        $userInfo['openid'] = $detail['openid'];
        $userInfo['signins'] = $detail['signins'];
        $userInfo['integral'] = $userInfo['score'];
        $userInfo['avatar'] = cdnurl($userInfo['avatar'],true);
        $userInfo['b_avatar'] = $userInfo['avatar'];
        //校验权限
        $store = Store::get(["user_id"=>$user]);
        if ($store){
            $userInfo['store'] = 1;
        }else{
            $userInfo['store'] = 0;
        }
        $this->success("获取成功",$userInfo);
    }

    /*
     * 签到
     */
    public function signin(){
        $user_id = $this->auth->id;
        $time = time()+3600*300;
        $detail = Detail::find(['user_id'=>$user_id]);
        //判断是否签到过
        $info = Signin::where("user_id",$user_id)->order("id","desc")->find();
        if ($info){
            $flag = false;
            if ($info->last_time == ''){
                //判断当天是否签到过
                $time1=date("Y-m-d",$time);
                $time2=date("Y-m-d",$info->time);
                $Date_time1=explode("-",$time1);
                $Date_time2=explode("-",$time2);
                if ($Date_time1[1] == $Date_time2[1] && $Date_time1[2] == $Date_time2[2]){
                    $this->success("今天已签到，明天再来吧");
                }else{
                    //判断是否连续
                    if (($Date_time1[0] == $Date_time2[0] && $Date_time1[1] == $Date_time2[1])){
                        if ($Date_time1[2] - $Date_time2[2] > 1){
                            $points = $this->config['points'];
                            $day = 1;
                        }else{
                            $points = bcadd($this->config['points'],$this->config['addup']);
                            $day = 2;
                            $flag = true;
                        }
                    }else{
                        $points = $this->config['points'];
                        $day = 1;
                    }
                }

            }else{
                //判断当天是否签到过
                $time1=date("Y-m-d",$time);
                $time2=date("Y-m-d",$info->time);
                $Date_time1=explode("-",$time1);
                $Date_time2=explode("-",$time2);
                if ($Date_time1[1] == $Date_time2[1] && $Date_time1[2] == $Date_time2[2]){
                    $this->success("今天已签到，明天再来吧");
                }
                //判断签到是否中断
                if (($Date_time1[0] == $Date_time2[0] && $Date_time1[1] == $Date_time2[1])){
                    if ($Date_time1[2] - $Date_time2[2] > 1){
                        $points = $this->config['points'];
                        $day = 1;
                    }else{
                        if ($detail->signins > $this->config['max']){
                            $points = $info->points;
                            $day = $detail->signins;
                        }else{
                            $points = $info->points + $this->config['addup'];
                            $day = $detail->signins;
                        }
                        $flag = true;
                    }
                }else{
                    $points = $this->config['points'];
                    $day = 1;
                }
            }
            //赠送积分
            Signin::create([
                "user_id"   =>  $user_id,
                "time"      =>  $time,
                "last_time" =>  $info->time,
                "points"    =>  $points
            ]);
            $detail->integral = $detail->integral + $this->config['points'];
            if ($flag == true){
                $detail->signins = $detail->signins+1;
            }else{
                $detail->signins = 1;
            }
            $detail->save();
            $before = $detail->integral;
            $after = $detail->integral + $this->config['points'];
            $memo = "累计签到".$day."天,赠送".$points."积分";
            //写入日志
            ScoreLog::create(['user_id' => $user_id, 'score' => $this->config['points'], 'before' => $before, 'after' => $after, 'memo' => $memo]);
            //更新连续签到天数

            $this->success("签到成功");
        }else{
            //赠送积分
            Signin::create([
                "user_id"   =>  $user_id,
                "time"      =>  $time,
                "last_time" =>  "",
                "points"    =>  $this->config['points']
            ]);
            $detail->integral = $detail->integral + $this->config['points'];
            $detail->save();
            $before = $detail->integral;
            $after = $detail->integral + $this->config['points'];
            $memo = "累计签到1天,赠送".$this->config['points']."积分";
            //写入日志
            ScoreLog::create(['user_id' => $user_id, 'score' => $this->config['points'], 'before' => $before, 'after' => $after, 'memo' => $memo]);
            $this->success("签到成功");
        }
    }
    /*
     * 退出登录
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error("请求方法异常");
        }
        $this->auth->logout();
        $this->success("退出登录成功");
    }
}
